from expression import *
import sys
sys.path.append(sys.path[0] + "/../LLVM")
from llvmhelper import llvmHelper
from llvm import *
from commonRoutines import commonRoutines

class scope(expression):
	def __init__(self, next):
		self.next = next
		self.numberOfVars = None
		self.functionScope = False
		self.firstScope = False

	def evaluate(self,env):
		return self.next.evaluate(env)

	def getNext(self):
		return self.next
	
	def __str__(self):
		return "(Scope "+ str(self.next) + ")"

	def setFunctionScope(self):
		self.functionScope = True

	def traverse(self, helper):
		helper.addScope()
		if(self.functionScope):
			functionArgs = helper.getStaticPassArgs()
			functionArgs.reverse()
			count = 0
			for a in functionArgs:
				#sys.stderr.write("Adding function arg: " + a + " at " + str(count) + "\n")
				helper.addVarToScope(a)
				count += 1
		
		self.next.traverse(helper)
		self.numberOfVars =  helper.getCurrentScope().getNumberOfVars()

		# add number of variables in current function - if this is first scope down?
		helper.retScope()
		
	def getContents(self):
		return self.next
		
	def setContents(self, newNext):
		self.next = newNext
		self.firstScope = True
	
	def toLLVM(self, helper):
	
		helper.descend("scope")

		c = commonRoutines(helper)
		
		eframeReg =  c.createEframe(self.numberOfVars, self.functionScope, self.firstScope)
		
		helper.incrementScopeDepth(eframeReg)
		
		self.next.toLLVM(helper)
		
		helper.decrementScopeDepth()
#		sys.stderr.write("\nScope Returns: " + str(helper.getReturns()))
		helper.setLabel(helper.getLastLabel())
		helper.ascend(helper.getReturns()[0])
		
		
